<!-- eslint-disable vue/multi-word-component-names -->
<!-- eslint-disable no-template-curly-in-string -->
<template>
    <div>
        <el-card class="box-card">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>用户管理</el-breadcrumb-item>
                <el-breadcrumb-item>用户列表</el-breadcrumb-item>
            </el-breadcrumb>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-input placeholder="请输入内容" v-model="search">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList(1)" ></el-button>
                    </el-input>
                </el-col>
                <el-col :span="6">
                    <el-button type="primary" @click="addUserdialogVisible = true">增加用户</el-button>
                </el-col>
            </el-row>
            <el-table :data="userList" border style="width: 100%">
                <el-table-column type="index"  label="序号" > </el-table-column>
                <el-table-column prop="username" label="用户名" > </el-table-column>
                <el-table-column prop="phone" label="电话" > </el-table-column>
                <el-table-column prop="is_active" label="激活" >
                  <template slot-scope="{row}">
                    <el-switch v-if="row.id !==1" v-model="row.is_active" @change="handleIsActive(row)" ></el-switch>
                     <span style="margin-left: 10px"></span>
                  </template>
                </el-table-column>
                <el-table-column prop="is_superuser" label="管理员">
                  <template slot-scope="{row}">
                     {{ row.is_superuser ?  '是' : '否' }}
                  </template>
                </el-table-column>
                <el-table-column  label="操作">
                  <template v-if="row.id !==1" slot-scope="{row}">
                    <el-tooltip content="分配角色"  effect="light" >
                      <el-button  @click="handleSetRole(row)" type="info" icon="el-icon-setting" size="mini"></el-button>
                    </el-tooltip>
                    <el-tooltip content="修改"  effect="light" >
                      <el-button  @click="handleEditUser(row)" type="success" icon="el-icon-edit" size="mini"></el-button>
                    </el-tooltip>
                    <el-tooltip content="删除"  effect="light" >
                      <el-button @click="handleDelUser(row.id)" type="danger" icon="el-icon-delete" size="mini"></el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
            </el-table>
            <el-pagination
               @current-change="handleCurrentChange"
               :current-page="pagination.page"
               :page-size="pagination.size"
               layout="total, prev, pager, next, jumper"
               :total="pagination.total">
            </el-pagination>
        </el-card>
        <!-- 修改对话框 -->
        <el-dialog
             title="修改用户"
             :visible.sync="editUserdialogVisible" @close="resetForm('editUser')">
             <el-form :model="editUserForm" :rules="editUserRules" ref="editUser" label-width="100px" >
               <el-form-item label="用户名" >
                 {{editUserForm.username}}
               </el-form-item>
               <el-form-item label="电子邮箱" prop="email">
                 <el-input v-model="editUserForm.email"></el-input>
               </el-form-item>
               <el-form-item label="电话号码" prop="phone">
                 <el-input v-model="editUserForm.phone"></el-input>
               </el-form-item>
             </el-form>
              <span slot="footer" class="dialog-footer">
              <el-button @click="editUserdialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="editUser">确 定</el-button>
             </span>
        </el-dialog>
        <!-- 添加窗口 -->
        <el-dialog
             title="新增用户"
             :visible.sync="addUserdialogVisible" @close="resetForm('addUser')">
             <el-form :model="addUserForm" :rules="addUserRules" ref="addUser" label-width="100px" >
               <el-form-item label="用户名" prop="username">
                 <el-input v-model="addUserForm.username"></el-input>
               </el-form-item>
               <el-form-item label="密码" prop="password">
                 <el-input v-model="addUserForm.password"></el-input>
               </el-form-item>
               <el-form-item label="确认密码" prop="checkpass">
                 <el-input v-model="addUserForm.checkpass"></el-input>
               </el-form-item>
               <el-form-item label="电子邮箱" prop="email">
                 <el-input v-model="addUserForm.email"></el-input>
               </el-form-item>
               <el-form-item label="电话号码" prop="phone">
                 <el-input v-model="addUserForm.phone"></el-input>
               </el-form-item>
             </el-form>
              <span slot="footer" class="dialog-footer">
              <el-button @click="addUserdialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="addUser">确 定</el-button>
             </span>
        </el-dialog>
          <!-- 分配角色窗口 -->
        <el-dialog
             :title="currentRow.username  +  '分配角色'"
             :visible.sync="setRoledialogVisible" @close="resetTree">
              <el-tree :data="dataList"
              node-key="id"
              :default-checked-keys="selectedIds"
              ref="tree" :props="{
                                  label: 'name'
                                }"
              show-checkbox></el-tree>
              <span slot="footer" class="dialog-footer">
              <el-button @click="setRoledialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="setRole">确 定</el-button>
             </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
  created() {
    this.getUserList()
  },
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value !== this.addUserForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      search: '',
      addUserdialogVisible: false,
      addUserForm: {
        username: '',
        password: '',
        email: '',
        checkpass: '',
        phone: ''
      },
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 4, max: 16, message: '长度在 4 到 16 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 4, max: 16, message: '长度在 4 到 16 个字符', trigger: 'blur' }
        ],
        checkpass: [
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          { min: 4, max: 16, message: '长度在 4 到 16 个字符', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ]

      },
      userList: [
      ],
      pagination: {
        total: 0,
        size: 20,
        page: 1
      },
      // 修改用户
      editUserdialogVisible: false,
      editUserForm: {
        username: '',
        email: '',
        phone: ''
      },
      editUserRules: {
      },
      dataList: [],
      setRoledialogVisible: false,
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      selectedIds: [],
      currentRow: {}
    }
  },
  methods: {
    resetForm(name) {
      // const name = 'addUser'
      // console.log('++++++++++++++++++++')
      console.log(name)
      this.$refs[name].resetFields()
    },
    resetTree() {
      this.dataList = []
      // this.$refs.tree
      this.$refs.tree.setCheckedKeys([])
      this.currentRow = {}
    },
    addUser() {
      const name = 'addUser'
      this.$refs[name].validate(async (valid) => {
        if (valid) {
          const { data: response } = await this.$http.post('users/mgr/', this.addUserForm)
          if (response.code) {
            return this.$message.error(response.message)
          }
          this.getUserList(this.pagination.page)
          this.addUserdialogVisible = false
          this.$message('用户添加成功')
        }
      })
    },
    async getUserList(page = 1) {
      if (!page) {
        page = 1
      }
      const { data: response } = await this.$http.get('users/mgr/', {
        params: {
          page,
          search: this.search
        }
      })
      if (response.code) {
        return this.$message.error(response.message)
      }
      this.userList = response.results
      this.pagination = response.pagination
    },
    handleCurrentChange(page) {
      this.getUserList(page)
    },
    async handleIsActive(row) {
      const { id } = row
      const { data: response } = await this.$http.patch(`users/mgr/${id}/`, { is_active: row.is_active })
      if (response.code) {
        return this.$message.error(response.message)
      }
      // 刷新当前页
    },
    handleEditUser(row) {
      // const name =  'editUser'
      this.editUserForm = row
      this.editUserdialogVisible = true
    },
    handleDelUser (id) {
      this.$msgbox.confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async () => {
        const { data: response } = await this.$http.delete(`users/mgr/${id}/`)
        if (response.code) {
          return this.$message.error(response.message)
        }
        this.getUserList(this.pagination.page)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    editUser() {
      const name = 'editUser'
      const { id, email, phone } = this.editUserForm
      this.$refs[name].validate(async (valid) => {
        if (valid) {
          const { data: response } = await this.$http.patch(`users/mgr/${id}/`, {
            email, phone
          })
          if (response.code) {
            return this.$message.error(response.message)
          }
          this.editUserdialogVisible = false
          this.$message('用户修改成功')
          this.getUserList(this.pagination.page)
        }
      })
    },
    async handleSetRole(row) {
      // 1 显示所有可用的角色们 2 我自己有什么角色，打勾
      const { id } = row
      const { data: response } = await this.$http.get(`users/mgr/${id}/roles/`)
      if (response.code) {
        return this.$message.error(response.message)
      }
      this.dataList = response.allRoles
      this.selectedIds = response.roles.map(obj => obj.id) // 前后端处理都可以，返回的是多个对象 [{'id':},{'id':}]
      this.currentRow = response
      this.setRoledialogVisible = true
    },
    async setRole() {
      const { id } = this.currentRow
      console.log(this.$refs.tree.getCheckedKeys())
      const groups = this.$refs.tree.getCheckedKeys()
      const { data: response } = await this.$http.put(`users/mgr/${id}/roles/`, {
        groups
      })
      if (response.code) {
        return this.$message.error(response.message)
      }
      this.setRoledialogVisible = false
    }
    // async handleSearch () {
    //   const { data: response } = await this.$http.get('users/', {
    //     params: {
    //       username: this.search
    //     }
    //   })
    //   if (response.code) {
    //     return this.$message.error(response.message)
    //   }
    //   this.userList = response.results
    //   this.pagination = response.pagination
    // }
  }

}
</script>

<style lang="less" scoped>
.el-breadcrumb {
    margin-bottom: 15px;
}
</style>